package com.lykj.llw.box.ui.fragment

import android.content.Intent
import android.graphics.Typeface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import app.dinus.com.itemdecoration.LinearDividerItemDecoration
import com.blankj.utilcode.util.ClipboardUtils
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.dinuscxj.itemdecoration.GridDividerItemDecoration
import com.google.android.material.appbar.AppBarLayout
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.lykj.lib_base.app.BaseApplication
import com.lykj.lib_base.base.BaseFragment
import com.lykj.lib_base.bus.FlowBus
import com.lykj.lib_base.component.GlideApp
import com.lykj.lib_base.constants.BConstants
import com.lykj.lib_base.data.bean.response.UserInfoResponse
import com.lykj.lib_base.internal.extfun.clickWithTrigger
import com.lykj.lib_base.internal.utils.ToastUtils
import com.lykj.lib_base.net.http.CustomResponseBodyObserver
import com.lykj.lib_base.net.http.RetrofitManager
import com.lykj.llw.box.R
import com.lykj.llw.box.adapter.MineOptionAdapter
import com.lykj.llw.box.adapter.PlayingAdapter
import com.lykj.llw.box.data.bean.response.PlayingListResponse
import com.lykj.llw.box.data.bean.response.agent.AgentRTDataResponse
import com.lykj.llw.box.data.bean.response.agent.AgentUserInfoResponse
import com.lykj.llw.box.data.model.MineOptionModel
import com.lykj.llw.box.databinding.FrgMineBinding
import com.lykj.llw.box.ui.activity.agent.AgentAccountActivity
import com.lykj.llw.box.ui.activity.agent.AgentGiftCodeActivity
import com.lykj.llw.box.ui.activity.agent.AgentInviteActivity
import com.lykj.llw.box.ui.activity.agent.AgentVoucherActivity
import com.lykj.llw.box.ui.activity.agent.AgentWithdrawalActivity
import com.lykj.llw.box.ui.activity.AwardTaskActivity
import com.lykj.llw.box.ui.activity.GameDetailActivity
import com.lykj.llw.box.ui.activity.MyBillingActivity
import com.lykj.llw.box.ui.activity.MyCouponActivity
import com.lykj.llw.box.ui.activity.MyGiftBagActivity
import com.lykj.llw.box.ui.activity.MyKeFuActivity
import com.lykj.llw.box.ui.activity.PTBRechargeActivity
import com.lykj.llw.box.ui.activity.SettingActivity
import com.lykj.llw.box.ui.activity.WelfareExchangeActivity
import com.lykj.llw.box.ui.activity.agent.AgentDataQueryActivity
import com.lykj.llw.box.ui.activity.agent.AgentLookEarningActivity
import com.lykj.llw.box.ui.activity.agent.AgentSettingActivity
import com.lykj.llw.box.ui.activity.agent.AgentUpgradeDescActivity
import com.lykj.llw.box.ui.diafrg.agent.AgentServerCodeDiaFrg
import io.reactivex.disposables.Disposable
import okhttp3.ResponseBody

/**
 * ================================================
 * Frag-我的
 * ================================================
 *
 * @author gosha
 * @date 2023/10/12-18:09
 */
class MineFragment : BaseFragment() {
    lateinit var binding: FrgMineBinding

    private val mAdapter = MineOptionAdapter()
    private val mData = ArrayList<MineOptionModel>()

    private val mPlayingAdapter = PlayingAdapter()
    private val mPlayingData = ArrayList<PlayingListResponse.DataDTO>()

    private var mAgentUserInfo: AgentUserInfoResponse.DataDTO? = null

    private var mCurrentIndex = 0
    private var mIsCanScroll = true

    private var mShowAgent = false


    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        binding = FrgMineBinding.inflate(layoutInflater)
        initUI()
        initData()
        setListener()
        return binding.root
    }

    override fun onResume() {
        super.onResume()
        ImmersionBar.with(this)
            .statusBarDarkFont(true) //状态栏字体是深色，不写默认为亮色
            .navigationBarDarkIcon(true)
            .hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR)
            .navigationBarEnable(false)
            .init()

        if (null != BaseApplication.instance?.getAgentUserInfo() && mShowAgent) {
            //代理相关接口
            obtainAgentUserInfo()
            obtainAgentRTData()
            binding.corltUser.visibility = View.GONE
            binding.vAgent.root.visibility = View.VISIBLE
        } else {
            obtainUserInfo()
            switchTab(mCurrentIndex)

            binding.corltUser.visibility = View.VISIBLE
            binding.vAgent.root.visibility = View.GONE
        }
    }

    //获取代理用户信息
    private fun obtainAgentUserInfo() {
        RetrofitManager.instance.obtainAgentInfo(object :
            CustomResponseBodyObserver<ResponseBody>() {
            override fun onSubscribe(d: Disposable) {
                addDisposables(this@MineFragment, d)
            }

            override fun specificHandle(responseBody: String) {
                val bean = GsonUtils.fromJson(responseBody, AgentUserInfoResponse::class.java)
                mAgentUserInfo = bean.data

                binding.vAgent.tvDlMoney.text = "${bean.data.money}"
                binding.vAgent.tvMonthEarning.text = "${bean.data.dailiRatio}%"
                binding.vAgent.tvWeekEarning.text = "${bean.data.weekSumMoney}"
                binding.vAgent.tvTodayEarning.text = "${bean.data.daySumMoney}"

                var str = "${bean.data.level}"
                binding.vAgent.tvDlLevel.text = "LV$str"
                binding.vAgent.tvDlNickName.text =
                    "${
                        if (bean.data.nickname.isNullOrEmpty()) "${
                            bean.data.tel.substring(
                                0,
                                3
                            )
                        }****${bean.data.tel.substring(7)}" else bean.data.nickname
                    }"

                binding.vAgent.tvDlAccount.text =
                    "ID：${
                        bean.data.tel.substring(
                            0,
                            3
                        )
                    }****${bean.data.tel.substring(7)}"
                binding.vAgent.tvEarningDesc.text = "至尊黑金LV${bean.data.level}-收益"
                binding.vAgent.tvDlRegisterNum.text = "${bean.data.loginNum}"

                if (!bean.data?.headPic.isNullOrBlank()) {
                    GlideApp.with(this@MineFragment)
                        .load(bean.data?.headPic)
                        .circleCrop()
                        .transition(DrawableTransitionOptions.withCrossFade())
                        .into(binding.vAgent.ivDlAvatar)
                } else {
                    binding.vAgent.ivDlAvatar.setImageResource(R.mipmap.ic_default_avater)
                }
            }

            override fun handleException(ret: String, msg: String?) {
                msg?.let {
                    ToastUtils.showShort(requireContext(), it)
                }
            }
        })
    }

    //获取代理实时数据
    private fun obtainAgentRTData() {
        RetrofitManager.instance.obtainRTData(object : CustomResponseBodyObserver<ResponseBody>() {
            override fun onSubscribe(d: Disposable) {
                addDisposables(this@MineFragment, d)
            }

            override fun specificHandle(responseBody: String) {
                val bean = GsonUtils.fromJson(responseBody, AgentRTDataResponse::class.java)

                if (bean.data.size >= 1) {
                    binding.vAgent.lltRt1.visibility = View.VISIBLE
                    binding.vAgent.tvPlayerAccount1.text = "${bean.data[0].username}"
                    binding.vAgent.tvTime1.text = "${bean.data[0].time}"
                    binding.vAgent.tvCharge1.text = "${bean.data[0].money}"
                    binding.vAgent.tvGameName1.text = "${bean.data[0].gameName}"
                }
                if (bean.data.size >= 2) {
                    binding.vAgent.lltRt2.visibility = View.VISIBLE
                    binding.vAgent.tvPlayerAccount2.text = "${bean.data[1].username}"
                    binding.vAgent.tvTime2.text = "${bean.data[1].time}"
                    binding.vAgent.tvCharge2.text = "${bean.data[1].money}"
                    binding.vAgent.tvGameName2.text = "${bean.data[1].gameName}"
                }
                if (bean.data.size >= 3) {
                    binding.vAgent.lltRt3.visibility = View.VISIBLE
                    binding.vAgent.tvPlayerAccount3.text = "${bean.data[2].username}"
                    binding.vAgent.tvTime3.text = "${bean.data[2].time}"
                    binding.vAgent.tvCharge3.text = "${bean.data[2].money}"
                    binding.vAgent.tvGameName3.text = "${bean.data[2].gameName}"
                }
            }

            override fun handleException(ret: String, msg: String?) {
                msg?.let {
                    ToastUtils.showShort(requireContext(), it)
                }
            }
        })
    }

    //获取用户信息
    private fun obtainUserInfo() {
        RetrofitManager.instance.obtainUserInfo(object :
            CustomResponseBodyObserver<ResponseBody>() {
            override fun onSubscribe(d: Disposable) {
                addDisposables(this@MineFragment, d)
            }

            override fun specificHandle(responseBody: String) {
                val bean = GsonUtils.fromJson(responseBody, UserInfoResponse::class.java)
                binding.tvNickName.text =
                    if (bean.data?.username.isNullOrBlank()) "野原新之助" else bean.data?.nickname
                binding.tvAccount.text = "账号：${bean.data?.username}"
                binding.tvPtbNum.text = "${bean.data?.ptbMoney}"
                binding.tvWaitUseNum.text = "${bean.data?.couponNum}"

                if (bean.data?.signState == 1) {
                    binding.tvSignIn.text = "已签到"
                    binding.tvSignIn.isEnabled = false
                }

                if (!bean.data?.avatar.isNullOrBlank()) {
                    GlideApp.with(this@MineFragment)
                        .load(bean.data?.avatar)
                        .circleCrop()
                        .transition(DrawableTransitionOptions.withCrossFade())
                        .into(binding.ivAvatar)
                } else {
                    binding.ivAvatar.setImageResource(R.mipmap.ic_default_avater)
                }
            }

            override fun handleException(ret: String, msg: String?) {
                msg?.let { LogUtils.e("$msg") }
            }
        })
    }

    //获取正在玩的游戏列表
    private fun obtainPlayingGames() {
        clearBodyParam()
        initBodyParam()
        mPlayingData.clear()
        mPlayingAdapter.notifyDataSetChanged()
        RetrofitManager.instance.obtainPlayedGames(bodyParams,
            object : CustomResponseBodyObserver<ResponseBody>() {
                override fun onSubscribe(d: Disposable) {
                    addDisposables(this@MineFragment, d)
                }

                override fun specificHandle(responseBody: String) {
                    val bean = GsonUtils.fromJson(responseBody, PlayingListResponse::class.java)

                    if (!bean.data.isNullOrEmpty()) {
                        mPlayingData.addAll(bean.data)
                        mIsCanScroll = mIsCanScroll || true
                    }

                    if (!mIsCanScroll) {
                        val lps = AppBarLayout.LayoutParams(
                            AppBarLayout.LayoutParams.MATCH_PARENT,
                            AppBarLayout.LayoutParams.MATCH_PARENT
                        )
                        lps.scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_NO_SCROLL
                        binding.cltContain.layoutParams = lps
                    }

                    mPlayingAdapter.notifyDataSetChanged()
                }

                override fun handleException(ret: String, msg: String?) {
                    msg?.let {
                        ToastUtils.showShort(requireContext(), it)
                    }
                }
            })
    }

    //获取正在玩的游戏列表
    private fun obtainMyCollect() {
        mPlayingData.clear()
        mPlayingAdapter.notifyDataSetChanged()
        RetrofitManager.instance.obtainMyCollect(
            object : CustomResponseBodyObserver<ResponseBody>() {
                override fun onSubscribe(d: Disposable) {
                    addDisposables(this@MineFragment, d)
                }

                override fun specificHandle(responseBody: String) {
                    val bean = GsonUtils.fromJson(responseBody, PlayingListResponse::class.java)

                    mPlayingData.clear()
                    if (!bean.data.isNullOrEmpty()) {
                        mPlayingData.addAll(bean.data)
                        mIsCanScroll = mIsCanScroll || true
                    }

                    if (!mIsCanScroll) {
                        val lps = AppBarLayout.LayoutParams(
                            AppBarLayout.LayoutParams.MATCH_PARENT,
                            AppBarLayout.LayoutParams.MATCH_PARENT
                        )
                        lps.scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_NO_SCROLL
                        binding.cltContain.layoutParams = lps
                    }

                    mPlayingAdapter.notifyDataSetChanged()
                }

                override fun handleException(ret: String, msg: String?) {
                    msg?.let {
                        ToastUtils.showShort(requireContext(), it)
                    }
                }
            })
    }


    //签到
    private fun signIn() {
        RetrofitManager.instance.receiverAwardTask(
            "2",
            object : CustomResponseBodyObserver<ResponseBody>() {
                override fun onSubscribe(d: Disposable) {
                    addDisposables(this@MineFragment, d)
                }

                override fun specificHandle(responseBody: String) {
                    ToastUtils.showShort(requireContext(), "签到成功")
                    //刷新签到信息
                    obtainUserInfo()
                }

                override fun handleException(ret: String, msg: String?) {
                    msg?.let { ToastUtils.showShort(requireContext(), it) }
                }
            })
    }

    override fun initUI() {
        if (!BConstants.isDebug) {
            binding.ivMsg.visibility = View.GONE
//            binding.tvCollection.visibility = View.GONE
        }

        FlowBus.with<String>(BConstants.BUS_KEY.AGENT_LOGIN_SUCCESS).register(requireActivity()) {
            binding.corltUser.visibility = View.GONE
            binding.vAgent.root.visibility = View.VISIBLE
        }

        FlowBus.with<String>(BConstants.BUS_KEY.AGENT_LOGOUT_SUCCESS).register(requireActivity()) {
            binding.corltUser.visibility = View.VISIBLE
            binding.vAgent.root.visibility = View.GONE
        }

        FlowBus.with<String>(BConstants.BUS_KEY.LOGIN_SUCCESS).register(requireActivity()) {
            binding.corltUser.visibility = View.VISIBLE
            binding.vAgent.root.visibility = View.GONE
        }
    }

    override fun initData() {
        //初始化我的页面列表
        val model = MineOptionModel("会员月卡", R.mipmap.ic_vip_month_card)
        val model2 = MineOptionModel("我的礼包", R.mipmap.ic_my_gift_bag)
        val model3 = MineOptionModel("福利兑换", R.mipmap.ic_welfare_exchange)
        val model4 = MineOptionModel("有奖任务", R.mipmap.ic_task_award)
        val model5 = MineOptionModel("我的账单", R.mipmap.ic_my_billing)
        val model6 = MineOptionModel("我的客服", R.mipmap.ic_contract_kefu)
        val model7 = MineOptionModel("至尊黑金", R.mipmap.ic_agent)

        mData.add(model)
        mData.add(model2)
        mData.add(model3)
        mData.add(model4)
        mData.add(model5)
        mData.add(model6)
        mData.add(model7)

        initRecyclerView()
        initPlayingRCV()
    }

    private fun initRecyclerView() {
        val gridLayoutManager = GridLayoutManager(requireContext(), 4)
        gridLayoutManager.orientation = GridLayoutManager.VERTICAL
        binding.rcvOption.layoutManager = gridLayoutManager
        binding.rcvOption.setHasFixedSize(true)
        val dividerItemDecoration = GridDividerItemDecoration(
            requireContext(), GridDividerItemDecoration.GRID_DIVIDER_VERTICAL
        )
        dividerItemDecoration.setVerticalDivider(
            resources.getDrawable(
                R.drawable.divider_15dp, resources.newTheme()
            )
        )
        dividerItemDecoration.setHorizontalDivider(
            resources.getDrawable(
                R.drawable.divider_0dp, resources.newTheme()
            )
        )
        binding.rcvOption.addItemDecoration(dividerItemDecoration)
        mAdapter.data = mData
        mAdapter.setOnItemClickListener { adapter, view, position ->
            when (mData[position].name) {
                "会员月卡" -> {
                    FlowBus.with<Int>(BConstants.BUS_KEY.HOME_SWITCH_NAV)
                        .post(requireActivity().lifecycleScope, 1)
                }

                "我的客服" -> {
                    startActivity(Intent(requireContext(), MyKeFuActivity::class.java))
                }

                "我的账单" -> {
                    startActivity(Intent(requireContext(), MyBillingActivity::class.java))
                }

                "有奖任务" -> {
                    startActivity(Intent(requireContext(), AwardTaskActivity::class.java))
                }

                "我的礼包" -> {
                    startActivity(Intent(requireContext(), MyGiftBagActivity::class.java))
                }

                "福利兑换" -> {
                    startActivity(Intent(requireContext(), WelfareExchangeActivity::class.java))
                }

                "至尊黑金" -> {
                    mShowAgent = true
                    if (null == BaseApplication.instance?.getAgentUserInfo()) {
                        AgentServerCodeDiaFrg().show(childFragmentManager, "服务商代码验证弹窗")
                    } else if (mShowAgent) {
                        //代理相关接口
                        obtainAgentUserInfo()
                        obtainAgentRTData()
                        binding.corltUser.visibility = View.GONE
                        binding.vAgent.root.visibility = View.VISIBLE
                    }
                }
            }
        }
        binding.rcvOption.adapter = mAdapter
    }

    private fun initPlayingRCV() {
        val linearLayoutManager = LinearLayoutManager(requireContext())
        linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
        binding.rcvPlaying.layoutManager = linearLayoutManager
        binding.rcvPlaying.setHasFixedSize(true)

        val dividerItemDecoration = LinearDividerItemDecoration(
            requireContext(), LinearDividerItemDecoration.LINEAR_DIVIDER_VERTICAL
        )
        dividerItemDecoration.setDivider(
            resources.getDrawable(
                R.drawable.divider_10dp, resources.newTheme()
            )
        )
        binding.rcvPlaying.addItemDecoration(dividerItemDecoration)
        mPlayingAdapter.data = mPlayingData
        val emptyView = View.inflate(requireContext(), R.layout.empty_playing, null)
        emptyView.findViewById<TextView>(R.id.tv_desc).text = "暂无数据"
        mPlayingAdapter.setEmptyView(emptyView)
        mPlayingAdapter.setOnItemClickListener { adapter, view, position ->
            val intent = Intent(requireContext(), GameDetailActivity::class.java)
            intent.putExtra("gid", mPlayingData[position].gid)
            startActivity(intent)
        }
        binding.rcvPlaying.adapter = mPlayingAdapter
    }

    private fun switchTab(index: Int) {
        mCurrentIndex = index
        binding.tvPlaying.setTextColor(ColorUtils.string2Int("#646464"))
        binding.tvPlaying.textSize = 13f
        binding.tvPlaying.typeface = Typeface.DEFAULT

        binding.tvCollection.setTextColor(ColorUtils.string2Int("#646464"))
        binding.tvCollection.textSize = 13f
        binding.tvCollection.typeface = Typeface.DEFAULT

        if (index == 0) {
            binding.tvPlaying.setTextColor(ColorUtils.string2Int("#2C2C2C"))
            binding.tvPlaying.textSize = 15f
            binding.tvPlaying.typeface = Typeface.DEFAULT_BOLD

            obtainPlayingGames()
        } else {
            binding.tvCollection.setTextColor(ColorUtils.string2Int("#2C2C2C"))
            binding.tvCollection.textSize = 15f
            binding.tvCollection.typeface = Typeface.DEFAULT_BOLD

            obtainMyCollect()
        }
    }

    override fun setListener() {
        binding.lltVip.clickWithTrigger(150) {
            mShowAgent = true
            if (null == BaseApplication.instance?.getAgentUserInfo()) {
                AgentServerCodeDiaFrg().show(childFragmentManager, "服务商代码验证弹窗")
            } else if (mShowAgent) {
                //代理相关接口
                obtainAgentUserInfo()
                obtainAgentRTData()
                binding.corltUser.visibility = View.GONE
                binding.vAgent.root.visibility = View.VISIBLE
            }
        }
        binding.tvSignIn.clickWithTrigger(300) {
            signIn()
        }

        binding.ivCopy.clickWithTrigger(300) {
            ClipboardUtils.copyText(binding.tvAccount.text.toString().replace("账号：", ""))
            ToastUtils.showShort(requireContext(), "已成功复制到剪切板")
        }


        binding.cltWallet.clickWithTrigger(300) {
            startActivity(Intent(requireContext(), PTBRechargeActivity::class.java))
        }

        binding.cltYhj.clickWithTrigger(300) {
            startActivity(Intent(requireContext(), MyCouponActivity::class.java))
        }

        binding.ivSetting.clickWithTrigger(300) {
            startActivity(Intent(requireContext(), SettingActivity::class.java))
        }

        binding.srfRefresh.setOnRefreshListener {
            if (null != BaseApplication.instance?.getAgentUserInfo()) {
                obtainAgentUserInfo()
                obtainAgentRTData()
            } else {
                obtainUserInfo()
                obtainPlayingGames()
            }
            it.finishRefresh(300)
        }

        //代理的页面
        binding.vAgent.fltWithdrawal.clickWithTrigger(300) {
            val intent = Intent(requireContext(), AgentWithdrawalActivity::class.java)
            intent.putExtra("amount", mAgentUserInfo?.money ?: 0.0)
            startActivity(intent)
        }

        binding.vAgent.cltVoucher.clickWithTrigger(300) {
            startActivity(Intent(requireContext(), AgentVoucherActivity::class.java))
        }

        binding.vAgent.cltAccountInfo.clickWithTrigger(300) {
            startActivity(Intent(requireContext(), AgentAccountActivity::class.java))
        }

//        binding.vAgent.cltInvite.clickWithTrigger(300) {
//            startActivity(Intent(requireContext(), AgentInviteActivity::class.java))
//        }

        binding.vAgent.cltGiftCode.clickWithTrigger(300) {
            ToastUtils.showShort(requireContext(), "该功能暂未开放")
            return@clickWithTrigger
            startActivity(Intent(requireContext(), AgentGiftCodeActivity::class.java))
        }

        binding.vAgent.lltDlUpdate.clickWithTrigger(300) {
            startActivity(Intent(requireContext(), AgentUpgradeDescActivity::class.java))
        }

        binding.vAgent.tvLookEarning.clickWithTrigger(300) {
            startActivity(Intent(requireContext(), AgentLookEarningActivity::class.java))
        }

        binding.vAgent.fltDataQuery.clickWithTrigger(300) {
            startActivity(Intent(requireContext(), AgentDataQueryActivity::class.java))
        }

        binding.vAgent.ivAgentSetting.clickWithTrigger(300) {
            startActivity(Intent(requireContext(), AgentSettingActivity::class.java))
        }

        binding.tvPlaying.clickWithTrigger(250) {
            switchTab(0)
        }

        binding.tvCollection.clickWithTrigger(250) {
            switchTab(1)
        }

        //切换到不同账号
        binding.vAgent.lltAgentHome.clickWithTrigger(150) {
            obtainUserInfo()
            switchTab(mCurrentIndex)

            binding.corltUser.visibility = View.VISIBLE
            binding.vAgent.root.visibility = View.GONE

            mShowAgent = false
        }
    }

    override fun onDestroy() {
        removeDisposables(this)
        super.onDestroy()
    }
}